package com.wrt.sps.mgt.page.controller;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wrt.sps.mgt.entity.Permission;
import com.wrt.sps.mgt.entity.Writing;
import com.wrt.sps.mgt.service.WritingService;

@Controller
@RequestMapping("/mgt/writing")
public class WritingPageController extends CommonPermission {

	@Value("${upload.pic: jpg, jpeg, png}")
	private String[] picformat;

	@Resource
	private WritingService writingService;
	
	/**
	 * 文章管理
	 */
	@GetMapping
	public String page(Writing.Type type, Model model) {
		Assert.notNull(type, "type must not be null!");
		model.addAttribute("typeName", type.name());
		model.addAttribute("titleName", Writing.typeName(type));
		currentUserPermissions(model, Permission.Group.WRITING);
		return "writing";
	}
	
	/**
	 * 
	 * 添加文章（页面跳转）
	 * 
	 * @param 文章类型  type
	 * @param model
	 * 
	 * @return 页面地址
	 */
	@RequiresPermissions("writing_add")
	@GetMapping("/add")
	public String add(Writing.Type type, Model model) {
		commonHandle(type, model);
		model.addAttribute("titleName", "新增" + Writing.typeName(type));
		return "edit_writing";
	}
	
	/**
	 * 
	 * 编辑文章（页面跳转）
	 * 
	 * @param 文章类型  type
	 * @param 文章主键  id
	 * @param model
	 * 
	 * @return 页面地址
	 */
	@RequiresPermissions("writing_edit")
	@GetMapping("/edit")
	public String update(Writing.Type type, Long id, Model model) {
		commonHandle(type, model);
		if (null == id || id == 0) {
			return null;
		}
		model.addAttribute("writing", writingService.findById(id));
		model.addAttribute("titleName", "更新" + Writing.typeName(type));
		return "edit_writing";
	}
	
	/**
	 * 
	 * 添加和编辑页面所需载入的类型名称
	 * 
	 * @param 文章类型  type
	 * @param model
	 */
	private void commonHandle(Writing.Type type, Model model) {
		Assert.notNull(type, "type must not be null!");
		model.addAttribute("typeName", type.name());
		model.addAttribute("uploadFormat", StringUtils.join(picformat, "|"));
		model.addAttribute("showUploadFormat", StringUtils.join(picformat, ","));
	}
	
}
